#define DEBUG
#include <cstdio>
#include <cassert>
#define MAXN 100000
#define MAXK 17

using namespace std;

class Tree {
public:
  int n, m, size[MAXN+1], fa[MAXN+1], big[MAXN+1], son[MAXN+1], to[MAXN+1], link[MAXN+1], lca[MAXN+1][MAXK+1], dep[MAXN+1], down[MAXN+1][MAXK+1][3], lent[MAXN+1];

  void add(int f, int s) {
    m++;
    to[m] = s;
    link[m] = son[f];
    son[f] = m;
    fa[s] = f;
  }

  void dfs(int o) { //size, dep, big, lca, lent
    size[o]=1;
    dep[o] = dep[fa[o]]+1;
    for (int i=son[o]; i; i=link[i]) {
      dfs(to[i]);
      size[o] += size[to[i]];
      lent[o] += lent[to[i]]+size[to[i]];
      big[o] = size[big[o]]<size[to[i]] ? to[i] : big[o];
      lca[to[i]][0] = o;
    }
  }

  void build() {
    dfs(1);
    for (int i=1; i<=n; i++) {
      if (big[i]) {
	down[i][0][0] = big[i];
	down[i][0][1] = size[i]-2*size[big[i]];
	down[i][0][2] = size[i]-size[big[i]];
      }	
    }
    for (int j=1; j<=MAXK; j++) {
      for (int i=1; i<=n; i++) {
	lca[i][j] = lca[lca[i][j-1]][j-1];
	int t=down[i][j-1][0];
	down[i][j][0]=down[t][j-1][0];
	if (down[i][j][0]) {
	  down[i][j][1]=down[i][j-1][1]+down[t][j-1][1]+down[i][j-1][2]*(1<<(j-1));
	  down[i][j][2]=down[i][j-1][2]+down[t][j-1][2];
	}
      }
    }
  }

  int getLca(int u, int v, int &len) {
    if (dep[u]<dep[v]) {
      len=u, u=v, v=len;
    }
    len=0;
    for (int i=MAXK; i>=0; i--) {
      if (dep[lca[u][i]]>=dep[v]) {
	len = len+(1<<i);
	u=lca[u][i];
      }
    }
    if (u==v) {
      return u;
    }
    for (int i=MAXK; i>=0; i--) {
      if (lca[u][i]!=lca[v][i]) {
	len = len+(1<<(i+1));
	u=lca[u][i], v=lca[v][i];
      }
    }
    len+=2;
    return fa[u];
  }

  int getAns(int x, int y) {
    int ret, lcalen, xs=0, ys;
    if (size[x]<size[y]) {
      ret=x, x=y, y=ret;
    }
    if (x==getLca(x, y, lcalen)) {
      ys=0;
      ret = lent[x];
    } else {
      ys=size[y];
      ret=lent[x]+lcalen*ys+lent[y];
    }

    int o=x;
    for (int i=MAXK; i>=0; i--) {
      if (down[o][i][0] && size[down[o][i][0]]*2>=size[x]+ys) {
	ret = ret+down[o][i][1]+(1<<i)*ys+(1<<i)*xs;
	xs += down[o][i][2];
	o = down[o][i][0];
      }
    }
    return ret;
  }
};

int main() {
  #ifdef DEBUG
  freopen("4639.in", "r", stdin);
  freopen("4639.out", "w", stdout);
  #endif

  static Tree tree;
  int n;
  scanf("%d", &n);
  tree.n = n;
  for (int i=2; i<=n; i++) {
    int fa;
    scanf("%d", &fa);
    tree.add(fa, i);
  }

  tree.build();
  int q;
  scanf("%d", &q);
  for (int i=1; i<=q; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    printf("%d\n", tree.getAns(x, y));
  }

  fclose(stdin);
  fclose(stdout);
  return 0;
}
